<template>
  <basic-container>
    <avue-crud
      :option="option"
      v-model:search="search"
      v-model:page="page"
      v-model="form"
      :table-loading="loading"
      :data="data"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template #menu-left>
        <el-button
          type="danger"
          icon="el-icon-delete"
          plain
          v-if="permission.qyClassesLessons_delete"
          @click="handleDelete"
          >删 除
        </el-button>
        <el-button type="warning" plain icon="el-icon-download" @click="handleExport"
          >导 出
        </el-button>

        <el-button type="danger" plain @click="handAdd">添加 </el-button>
      </template>

      <template #menu="{ row, index, size }">
        <el-button type="primary" :size="size" icon="el-icon-view" @click="handEdit(row, index)" >查看</el-button >
      </template>
    </avue-crud>
  </basic-container>

  <el-dialog title="添加课表" append-to-body v-model="excelBox" width="800px">
    <div
      style="
        display: flex;
        width: 100%;
        text-align: center;
        align-items: center;
        justify-content: center;
      "
    >
      <div style="text-align: left; width: 450px">
        <avue-form
          ref="lessonsfrom"
          :option="addoption"
          v-model="lessonsfrom"
          @submit="handleSubmit"
        >
        </avue-form>
      </div>
    </div>
  </el-dialog>

  <el-dialog title="编辑课表" append-to-body v-model="excelBox1" width="800px">
    <div
      style="
        display: flex;
        width: 100%;
        text-align: center;
        align-items: center;
        justify-content: center;
      "
    >
      <div style="text-align: left; width: 450px">
        <avue-form 
          :option="editoption"
          v-model="lessonsfrom"
          @submit="handleEditSubmit"
        >
        </avue-form>
      </div>
    </div>
  </el-dialog>

  <transition name="drawer-transition">
    <div class="contain" v-show="display">
      <div class="drawerTage" @click="display = false">X</div>
      <div class="drawer"></div>
    </div>
  </transition>
</template>

<script>
import { getList, getDetail, add, update, remove } from '@/api/classes/qyClassesLessons';

import option from '@/option/classes/qyClassesLessons';
import addoption from '@/option/classes/qyClassesLessonsAdd';
import editoption from '@/option/classes/qyClassesLessonsEdit';

import { mapGetters } from 'vuex';
import { exportBlob } from '@/api/common';
import { getToken } from '@/utils/auth';
import { downloadXls } from '@/utils/util';
import { dateNow } from '@/utils/date';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

export default {
  data() {
    return {
      form: {},
      query: {},
      search: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: option,
      display: false,
      excelBox: false,
      excelBox1:false,
      align: 'left',
      dicData: [],
      addoption:  addoption,
      editoption:  editoption,
      lessonsfrom: {}, 

      data: [],
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.qyClassesLessons_add, true),
        viewBtn: this.validData(this.permission.qyClassesLessons_view, true),
        delBtn: this.validData(this.permission.qyClassesLessons_delete, true),
        editBtn: this.validData(this.permission.qyClassesLessons_edit, true),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
  },
  methods: {
    handleSubmit(form, done) { 
      this.$refs.lessonsfrom.validate(valid => {
        if (valid) {
          let obj = { ...form };
          if (obj.teacherIds instanceof Array) {
            if (obj.teacherIds.length > 0) {
              obj.teacherIds = obj.teacherIds.join(',');
            } else {
              obj.teacherIds = '';
            }
          }

          obj.startTime = obj.startTime + ' 00:00:00';
          obj.endTime = obj.endTime + ' 00:00:00';

          add(obj).then(
            () => {
              this.onLoad(this.page);
              this.$message({
                type: 'success',
                message: '操作成功!',
              });
              done();
            },
            error => {
              // loading();
              window.console.log(error);
            }
          );
        }
      });
      done();
    },
    handleEditSubmit(form, done) { 
      
          let obj = { ...form };
          if (obj.teacherIds instanceof Array) {
            if (obj.teacherIds.length > 0) {
              obj.teacherIds = obj.teacherIds.join(',');
            } else {
              obj.teacherIds = '';
            }
          }

          obj.startTime = obj.startTime + ' 00:00:00';
          obj.endTime = obj.endTime + ' 00:00:00';

          add(obj).then(
            () => {
              this.onLoad(this.page);
              this.$message({
                type: 'success',
                message: '操作成功!',
              });
              done();
            },
            error => {
              // loading();
              window.console.log(error);
            }
          );
        
       
    },
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        error => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        error => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handAdd() {
      this.excelBox = !this.excelBox;
    },
    handEdit(row, index) {
      this.lessonsfrom = row;
      
      console.log(`output->row`, this.lessonsfrom);
      this.excelBox1 = true;
    },
    handleExport() {
      let downloadUrl = `/xrsk-qyClasses/qyClassesLessons/export-qyClassesLessons?${
        this.website.tokenHeader
      }=${getToken()}`;
      const {} = this.query;
      let values = {};
      this.$confirm('是否导出数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        NProgress.start();
        exportBlob(downloadUrl, values).then(res => {
          downloadXls(res.data, `课表${dateNow()}.xlsx`);
          NProgress.done();
        });
      });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;

      const {} = this.query;

      let values = {};

      getList(page.currentPage, page.pageSize, values).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;

        this.selectionClear();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.drawer-transition-enter-active,
.drawer-transition-leave-active {
  transition: transform 0.3s ease;
}
.drawer-transition-enter, .drawer-transition-leave-to /* .drawer-transition-leave-active for <2.1.8 */ {
  transform: translateX(100%);
}
.contain {
  position: relative;
  display: fixed;
  position: fixed;
  top: 0;
  right: 0;
  width: 550px;
  height: 100vh;
  z-index: 1000;
}
.drawer {
  position: fixed;
  top: 0;
  right: 0;
  padding: 10px 10px;
  width: 500px;
  height: 100vh;
  background-color: #fff;
  box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000;
}
.drawerTage {
  cursor: pointer;
  max-width: 100px;
  width: 100px;
  height: 50px;
  background-color: #fff;
  text-align: center;
  display: flex;
  align-items: center;
  border-radius: 10px 10px;
  padding-left: 10px;
  box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.1);
}
</style>
